package com.example.bookstore.security

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.web.access.AccessDeniedHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by IntelliJ IDEA.
 * User: lvshe
 * Date: 2019/8/13
 * Time: 21:10
 */
class AccessDeniedToJsonHandler : AccessDeniedHandler {

    override fun handle(request: HttpServletRequest, response: HttpServletResponse, accessDeniedException: AccessDeniedException) {
        response.contentType = "application/json; charset=UTF-8"
        response.status = HttpServletResponse.SC_FORBIDDEN
        val responseJson = hashMapOf("message" to "无权限访问 ${accessDeniedException.localizedMessage}")
        response.writer.write(MappingJackson2HttpMessageConverter().objectMapper.writeValueAsString(responseJson))

        response.writer.flush()
        response.writer.close()
    }

}